from flask import Blueprint, request
from common.libs.Helper import ops_renderJSON, iPagenation, ops_render
from common.models.plan import Plan

from application import db, app
from common.libs.DataHelper import getCurrentTime
import flask_excel as excel
from qiniu import Auth
from qiniu import put_data
from qiniu import BucketManager
from dateutil import rrule
import datetime

plan_page = Blueprint("plan_page", __name__)


@plan_page.route('/', methods=['GET', 'POST'])
def planindex():
    return ops_render("/plan/plan.html")


@plan_page.route('/plansearch', methods=['GET', 'POST'])
def plansearch():
    req = request.values
    plandate = req['plandate'] if "plandate" in req else ""
    year = req['year'] if "year" in req else ""
    companytwo = req['companytwo'] if "companytwo" in req else ""

    if plandate == "一月":
        sdate = year + "-01-01"
        edate = year + "-01-31"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                      Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                      Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})

    if plandate == "二月":
        sdate = year + "-02-01"
        edate = year + "-02-28"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                      Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                      Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})

    if plandate == "三月":
        sdate = year + "-03-01"
        edate = year + "-03-31"
        print(sdate, edate)
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                      Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                      Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})

    if plandate == "四月":
        sdate = year + "-04-01"
        edate = year + "-04-30"
        print(sdate, edate)
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                      Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                      Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})

    if plandate == "五月":
        sdate = year + "-05-01"
        edate = year + "-05-31"
        print(sdate, edate)
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                      Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                   Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})

    if plandate == "六月":
        sdate = year + "-06-01"
        edate = year + "-06-30"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                          Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                          Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})

    if plandate == "七月":
        sdate = year + "-07-01"
        edate = year + "-07-31"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                          Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                          Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})
    if plandate == "八月":
        sdate = year + "-08-01"
        edate = year + "-08-31"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                          Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                          Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})
    if plandate == "九月":
        sdate = year + "-09-01"
        edate = year + "-09-30"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                          Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                          Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})
    if plandate == "十月":
        sdate = year + "-10-01"
        edate = year + "-10-31"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                          Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                          Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})
    if plandate == "十一月":
        sdate = year + "-11-01"
        edate = year + "-11-30"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                          Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                          Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})
    if plandate == "十二月":
        sdate = year + "-12-01"
        edate = year + "-12-31"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                          Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                          Plan.plandate)
        return ops_render("/plan/plan.html", {"planindex": planindex})


# 新增计划
@plan_page.route('/addplan', methods=['GET', 'POST'])
def addplan():
    req = request.values
    name = req['name'] if "name" in req else ""
    companyone = req['companyone'] if "companyone" in req else ""
    companytwo = req['companytwo'] if "companytwo" in req else ""
    project = req['project'] if "project" in req else ""
    zbsize = req['zbsize'] if "zbsize" in req else ""
    zbfw = req['zbfw'] if "zbfw" in req else ""
    zbyt = req['zbyt'] if "zbyt" in req else ""
    classone = req['classone'] if "classone" in req else ""
    classtwo = req['classtwo'] if "classtwo" in req else ""
    plandate = req['plandate'] if "plandate" in req else ""
    bz = req['bz'] if "bz" in req else ""
    planstartdate = req['planstartdate'] if "planstartdate" in req else ""
    uid = req['uid'] if "uid" in req else ""
    plandate = plandate + "-02"
    planstartdate = planstartdate + "-02"

    index = Plan()
    index.companyone = companyone
    index.type = 1
    index.companytwo = companytwo
    index.name = name
    index.mark = 1
    index.uid = uid
    index.project = project
    index.zbsize = zbsize
    index.zbfw = zbfw
    index.zbyt = zbyt
    index.classone = classone
    index.classtwo = classtwo
    index.plandate = plandate
    index.bz = bz
    index.planstartdate = planstartdate
    index.created_time = index.updated_time = getCurrentTime()
    db.session.add(index)
    db.session.commit()

    return ops_renderJSON(msg="新建成功")


# 更新计划
@plan_page.route('/updataplan', methods=['GET', 'POST'])
def updataindex():
    req = request.values
    id = req['id'] if "id" in req else ""
    nowdate = req['nowdate'] if "nowdate" in req else ""
    startdate = req['startdate'] if "startdate" in req else ""
    bz = req['bz'] if "bz" in req else ""
    nowdate = nowdate + "-02"
    startdate = startdate + "-02"

    nowdate1 = datetime.date(*map(int, nowdate.split('-')))

    index = Plan.query.filter_by(id=id).first()
    plandate = str(index.plandate)
    plandate1 = datetime.date(*map(int, plandate.split('-')))
    months = rrule.rrule(rrule.MONTHLY, dtstart=plandate1, until=nowdate1).count()
    index.differ = months - 1
    index.nowdate = nowdate
    index.startdate = startdate
    index.bz=bz
    index.updated_time = getCurrentTime()
    db.session.add(index)
    db.session.commit()
    return ops_renderJSON(msg="更新成功")


def make_excel_list(data, column_names):
    list_data = []
    list_data.append(column_names)
    for item in data:
        tmp = [item.companyone, item.companytwo, item.project, item.name, item.zbsize, item.zbyt, item.zbfw,
               item.classone,
               item.classtwo, item.plandate, item.planstartdate, item.startdate, item.nowdate,
               item.differ]
        list_data.append(tmp)
    return list_data


excel.init_excel(app)


@plan_page.route("/export", methods=['GET'])
def export_records():
    req = request.values
    plandate = req['plandate'] if "plandate" in req else ""
    year = req['year'] if "year" in req else ""
    companytwo = req['companytwo'] if "companytwo" in req else ""

    if plandate == "第一季度":
        sdate = year + "-01-01"
        edate = year + "-03-31"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                      Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                      Plan.plandate)
        column_names = ['省公司', '城市公司', '项目', '工程名称', '招标总面积', '业态', '范围', '级别', '邀请招标', '申请招标日期', '计划进厂日期', '实际招标日期',
                    '实际进厂日期', '延期时长（月）']
        excel_data = make_excel_list(planindex, column_names)

    # app.logger.info(excel_data)

        return excel.make_response_from_array(excel_data, file_type='xls',
                                          file_name=year+companytwo+plandate+"纠偏数据",
                                          sheet_name='数据')

    if plandate == "第二季度":
        sdate = year + "-03-01"
        edate = year + "-06-30"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                      Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                      Plan.plandate)
        column_names = ['省公司', '城市公司', '项目', '工程名称', '招标总面积', '业态', '范围', '级别', '邀请招标', '申请招标日期', '计划进厂日期', '实际招标日期',
                        '实际进厂日期', '延期时长（月）']
        excel_data = make_excel_list(planindex, column_names)

        # app.logger.info(excel_data)

        return excel.make_response_from_array(excel_data, file_type='xls',
                                              file_name=year+companytwo+plandate+"纠偏数据",
                                              sheet_name='合同信息')

    if plandate == "第三季度":
        sdate = year + "-07-01"
        edate = year + "-09-30"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                      Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                      Plan.plandate)
        column_names = ['省公司', '城市公司', '项目', '工程名称', '招标总面积', '业态', '范围', '级别', '邀请招标', '申请招标日期', '计划进厂日期', '实际招标日期',
                        '实际进厂日期', '延期时长（月）']
        excel_data = make_excel_list(planindex, column_names)

        # app.logger.info(excel_data)

        return excel.make_response_from_array(excel_data, file_type='xls',
                                              file_name=year+companytwo+plandate+"纠偏数据",
                                              sheet_name='合同信息')

    if plandate == "第四季度":
        sdate = year + "-10-01"
        edate = year + "-12-31"
        planindex = Plan.query.filter(Plan.plandate <= edate,
                                      Plan.plandate >= sdate, Plan.companytwo == companytwo).order_by(Plan.type,
                                                                                                      Plan.plandate)
        column_names = ['省公司', '城市公司', '项目', '工程名称', '招标总面积', '业态', '范围', '级别', '邀请招标', '申请招标日期', '计划进厂日期', '实际招标日期',
                        '实际进厂日期', '延期时长（月）']
        excel_data = make_excel_list(planindex, column_names)

        # app.logger.info(excel_data)

        return excel.make_response_from_array(excel_data, file_type='xls',
                                              file_name=year+companytwo+plandate+"纠偏数据",
                                              sheet_name='合同信息')
